import { reqCartList,reqDeleteCartBySkuId,reqUpdateCheckedById } from '@/api';

const state = {
    cartList: []
};

const getters = {
    cartList(state) {
        return state.cartList[0] || {};
    },
};

const mutations = {
    GETCARTLIST(state,cartList) {
        state.cartList = cartList;
    }
};

const actions = {
    // 获取购物车列表
    async getCartList({commit}) {
        let res = await reqCartList();
        if(res.code == 200) {
            commit('GETCARTLIST',res.data);
        }
    },
    // 根据skuid删除购物车商品
    async deleteCartBySkuId({commit},skuId) {
        let res = await reqDeleteCartBySkuId(skuId);
        if(res.code == 200) {
           return "ok";
        }
        return Promise.reject(new Error("fail"));
    },
    // 修改购物车选中状态
    async updateCheckedById({commit},{skuId,isChecked}) {
        let res = await reqUpdateCheckedById(skuId,isChecked);
        if(res.code == 200) {
            return "ok";
         }
         return Promise.reject(new Error("fail"));
    },
    // 删除所有选中的购物车数据
    deleteAllCheckedCart({dispatch,getters}){
        let PromiseAll = [];
        getters.cartList.cartInfoList.forEach(item =>{
        let promise = item.isChecked == 1 ? dispatch('deleteCartBySkuId',item.skuId) : ''
            PromiseAll.push(promise);
        });
        return Promise.all(PromiseAll)
    },
    // 修改购物车全选状态
    updateAllIsChecked({dispatch,state},isChecked){
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item =>{
           let promise = dispatch('updateCheckedById',{skuId:item.skuId,isChecked})
           PromiseAll.push(promise)
        })
        return Promise.all(PromiseAll)
    }
};

export default {
    state,
    getters,
    mutations,
    actions
}